package com.zgjkhis.modules.system.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zgjkhis.exception.ServiceException;
import com.zgjkhis.modules.charges.domain.PrescriptionOrder;
import com.zgjkhis.modules.charges.service.LogisticsService;
import com.zgjkhis.modules.charges.service.PrescriptionService;
import com.zgjkhis.modules.charges.service.dto.LogisticsRouteDto;
import com.zgjkhis.modules.charges.service.dto.LogisticsStatusDto;
import com.zgjkhis.modules.system.domain.ApiChannel;
import com.zgjkhis.modules.system.domain.OrderAddress;
import com.zgjkhis.modules.system.domain.vo.ApiVo;
import com.zgjkhis.modules.system.domain.vo.RefundOrderVO;
import com.zgjkhis.modules.system.req.UpdateDeliveryReq;
import com.zgjkhis.modules.system.service.ApiChannelService;
import com.zgjkhis.modules.system.service.OrderAddressService;
import com.zgjkhis.modules.system.service.OrderService;
import com.zgjkhis.modules.util.CharUtil;
import com.zgjkhis.modules.util.JsonUtil;
import com.zgjkhis.modules.util.RSAUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ApiController
 * @Deacription TODO
 * @Author yzq
 * @Date 2021/7/12 14:48
 * @Version 1.0
 **/
@Api(tags = "订单管理：云享订单同步")
@RestController
@RequestMapping("/pst")
@Slf4j
public class ApiController {

    private final ApiChannelService apiChannelService;
    private final OrderService orderService;
    private final LogisticsService logisticsService;
    private final PrescriptionService prescriptionService;
    private final OrderAddressService orderAddressService;

    public ApiController(ApiChannelService apiChannelService,
                         OrderService orderService,
                         PrescriptionService prescriptionService,
                         LogisticsService logisticsService, OrderAddressService orderAddressService) {
        this.apiChannelService = apiChannelService;
        this.orderService = orderService;
        this.logisticsService = logisticsService;
        this.prescriptionService = prescriptionService;
        this.orderAddressService = orderAddressService;
    }

    @PostMapping(value = "/createOrder")
    @ApiOperation("创建订单")
    public ResponseEntity<Object> createOrder(@RequestBody ApiVo apiVo) {
        ApiChannel apiChannel = apiChannelService.getOne(Wrappers.<ApiChannel>query().lambda().eq(ApiChannel::getStatus, 0).eq(ApiChannel::getAppId, apiVo.getAppId()));
        if (CharUtil.isEmpty(apiChannel)) {
            throw new ServiceException("渠道不存在");
        }
        String data = RSAUtil.decode(apiChannel.getPrivateKey(), apiVo.getData());
        JSONObject order = orderService.createOrder(data, apiChannel);
        return new ResponseEntity<>(order, HttpStatus.OK);
    }

    @PostMapping(value = "/queryLogistics")
    @ApiOperation("查询物流")
    public ResponseEntity<List<LogisticsRouteDto>> queryLogistics(@Validated @RequestBody ApiVo apiVo) {
        ApiChannel apiChannel = apiChannelService.getOne(Wrappers.<ApiChannel>query().lambda().eq(ApiChannel::getStatus, 0).eq(ApiChannel::getAppId, apiVo.getAppId()));
        if (CharUtil.isEmpty(apiChannel)) {
            throw new ServiceException("渠道不存在");
        }
        String data = RSAUtil.decode(apiChannel.getPrivateKey(), apiVo.getData());
        JSONObject json = JSON.parseObject(data);
        String orderNo = json.getString("orderNo");
        if (CharUtil.isEmpty(orderNo)) {
            throw new ServiceException("orderNo不能为null");
        }
        return new ResponseEntity(this.logisticsService.queryLogistics(orderNo), HttpStatus.OK);
    }

    @PostMapping(value = "/queryLogisticsStatus")
    @ApiOperation("查询物流状态")
    public ResponseEntity<List<LogisticsStatusDto>> queryLogisticsStatus(@Validated @RequestBody ApiVo apiVo) {
        ApiChannel apiChannel = apiChannelService.getOne(Wrappers.<ApiChannel>query().lambda().eq(ApiChannel::getStatus, 0).eq(ApiChannel::getAppId, apiVo.getAppId()));
        if (CharUtil.isEmpty(apiChannel)) {
            throw new ServiceException("渠道不存在");
        }
        String data = RSAUtil.decode(apiChannel.getPrivateKey(), apiVo.getData());
//        String data = apiVo.getData();
        JSONObject json = JSON.parseObject(data);
        String orderNo = json.getString("orderNo");
        if (CharUtil.isEmpty(orderNo)) {
            throw new ServiceException("orderNo不能为null");
        }
        PrescriptionOrder order = this.prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, orderNo));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        return new ResponseEntity(this.logisticsService.requestStatus(orderNo), HttpStatus.OK);
    }

    @PostMapping(value = "refundOrder")
    @ApiOperation("订单退费")
    public ResponseEntity<Object> refundOrder(@Validated @RequestBody ApiVo apiVo) {
        ApiChannel apiChannel = apiChannelService.getOne(Wrappers.<ApiChannel>query().lambda().eq(ApiChannel::getStatus, 0).eq(ApiChannel::getAppId, apiVo.getAppId()));
        if (CharUtil.isEmpty(apiChannel)) {
            throw new ServiceException("渠道不存在");
        }
        String data = RSAUtil.decode(apiChannel.getPrivateKey(), apiVo.getData());
        JSONObject json = JSON.parseObject(data);
        if (CharUtil.isEmpty(json)) {
            throw new ServiceException("参数不能为空");
        }
        log.info("退款报文：" + data);
        RefundOrderVO refundOrderVO = JsonUtil.jsonString2Obj(data, RefundOrderVO.class);
//        String pstNo=json.getString("pstNo");
//        String msg=json.getString("msg");
//        Integer type=json.getInteger("type");
//        String refundTime=json.getString("refundTime");
        if (CharUtil.isEmpty(refundOrderVO.getOrderNo())) {
            throw new ServiceException("订单号不能为空");
        }
        if (CharUtil.isEmpty(refundOrderVO.getMsg())) {
            throw new ServiceException("退款原因不能为空");
        }
        if (CharUtil.isEmpty(refundOrderVO.getRefundTime())) {
            throw new ServiceException("退款日期不能为空");
        }
        if (CharUtil.isEmpty(refundOrderVO.getActRefund())) {
            refundOrderVO.setActRefund("0");
//            throw new ServiceException("实际退款不能为空");
        }
        if (CharUtil.isEmpty(refundOrderVO.getType())) {
            refundOrderVO.setType(2);
        }

        PrescriptionOrder order = prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, refundOrderVO.getOrderNo()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("查无此订单");
        }
        if (!apiChannel.getAppId().equals(order.getSourceId())) {
            throw new ServiceException("查无此单");
        }

        if (order.getPayStatus() == 4) {
            if (!CharUtil.isEmpty(order.getCirOrderNo())) {
                String[] orderNos = order.getCirOrderNo().split(",");
                int count = 0;
                for (String orderNo : orderNos) {
                    PrescriptionOrder tempOrder = prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, orderNo));
                    if (tempOrder.getPayStatus() == 4) {
                        count++;
                    }
                }
                if (count >= orderNos.length) {
                    throw new ServiceException("订单已全部退款,退款失败");
                }
            } else {
                throw new ServiceException("订单已全部退款,退款失败");
            }
        }

//        if(1==refundOrderVO.getType()){
//            //部分退款
//            JSONArray array=json.getJSONArray("refundInfoList");
//            List<RefundInfoVO> list=JsonUtil.JSONString2List(array.toJSONString(),RefundInfoVO.class);
//            refundOrderVO.setInfoList(list);
//        }
        return orderService.refundOrder(refundOrderVO, order);
    }

    @PostMapping(value = "/updateDelivery")
    @ApiOperation("邮寄自取修改")
    public ResponseEntity<Object> updateDelivery(@RequestBody ApiVo apiVo) {
        ApiChannel apiChannel = apiChannelService.getOne(Wrappers.<ApiChannel>query().lambda().eq(ApiChannel::getStatus, 0).eq(ApiChannel::getAppId, apiVo.getAppId()));
        if (CharUtil.isEmpty(apiChannel)) {
            throw new ServiceException("渠道不存在");
        }
        String data = RSAUtil.decode(apiChannel.getPrivateKey(), apiVo.getData());
        UpdateDeliveryReq deliveryReq = JsonUtil.jsonString2Obj(data, UpdateDeliveryReq.class);
        if (CharUtil.isEmpty(deliveryReq.getOrderNo())) {
            throw new ServiceException("订单号不能为空");
        }
        if (CharUtil.isEmpty(deliveryReq.getDeliveryType()) || (1 != deliveryReq.getDeliveryType() && 2 != deliveryReq.getDeliveryType())) {
            throw new ServiceException("邮寄自提方式错误");
        }
        if (1 == deliveryReq.getDeliveryType() && CharUtil.isEmpty(deliveryReq.getOrderAddress())) {
            throw new ServiceException("邮寄地址不能为空");
        }
        PrescriptionOrder order = prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, deliveryReq.getOrderNo()));
        if (CharUtil.isEmpty(order)) {
            throw new ServiceException("订单不存在");
        }
        List<PrescriptionOrder> list = new ArrayList<>();
        //判断是否存在流转订单
        if (!CharUtil.isEmpty(order.getCirOrderNo())) {
            list = prescriptionService.list(Wrappers.<PrescriptionOrder>query().lambda().in(PrescriptionOrder::getOrderNo, Arrays.asList(order.getCirOrderNo().split(","))));
        }
        if (CharUtil.isEmpty(list)) {
            list = new ArrayList<>();
        }
        list.add(order);

        for (PrescriptionOrder tempOrder : list) {
            PrescriptionOrder temp = new PrescriptionOrder();
            temp.setDeliveryType(deliveryReq.getDeliveryType());
            temp.setId(tempOrder.getId());
            prescriptionService.updateById(temp);
            if (1 == deliveryReq.getDeliveryType()) {
                OrderAddress address = orderAddressService.getOne(Wrappers.<OrderAddress>query().lambda().eq(OrderAddress::getOrderNo, tempOrder.getOrderNo()));
                OrderAddress tempOrderAddress = deliveryReq.getOrderAddress();
                OrderAddress orderAddress = new OrderAddress();
                BeanUtils.copyProperties(tempOrderAddress, orderAddress);
                orderAddress.setOrderNo(tempOrder.getOrderNo());
                orderAddress.setPharmacyId(tempOrder.getPharmacyId());
                orderAddress.setCreateTime(new Date());
                if (!CharUtil.isEmpty(address)) {
                    orderAddress.setId(address.getId());
                }
                orderAddressService.saveOrUpdate(orderAddress);
            }
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }
}
